package org.jeecg.modules.bid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.bid.entity.Bid;
import org.jeecg.modules.bid.mapper.BidMapper;
import org.jeecg.modules.bid.service.IBidService;
import org.jeecg.modules.lottery.entity.Lottery;
import org.jeecg.modules.lottery.service.ILotteryService;
import org.jeecg.modules.message.service.IProcurementMessageService;
import org.jeecg.modules.purchase.entity.PurchasePlan;
import org.jeecg.modules.purchase.service.IPurchasePlanService;
import org.jeecg.modules.supplier.entity.ProcUserSupplierRelation;
import org.jeecg.modules.supplier.entity.Supplier;
import org.jeecg.modules.supplier.service.IProcUserSupplierRelationService;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BidServiceImpl extends ServiceImpl<BidMapper, Bid> implements IBidService {

    @Autowired
    private BidMapper bidMapper;

    @Autowired
    private ILotteryService lotteryService;

    @Autowired
    private ISupplierService supplierService;

    @Autowired
    private IPurchasePlanService purchasePlanService;
    @Autowired
    private IProcurementMessageService procurementMessageService;
    @Autowired
    private IProcUserSupplierRelationService procUserSupplierRelationService;

    /**
     * 根据采购方案ID和投标状态查询供应商列表
     * @param bidStatus 投标状态
     * @return 供应商列表
     */
    public List<Supplier> getSuppliersByBidStatus( String bidStatus) {
        QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("bid_status", bidStatus);
        List<Bid> bidList = bidMapper.selectList(queryWrapper);

        // 从投标记录中获取供应商ID，并查询对应的供应商信息
        return bidList.stream()
                .map(bid -> supplierService.getById(bid.getSupplierId()))
                .filter(supplier -> supplier != null) // 过滤掉可能的null值
                .collect(Collectors.toList());
    }

    /**
     * 根据供应商ID查询抽签信息
     * @param supplierId 供应商ID
     * @return 供应商抽签记录列表
     */

    public List<Bid> getSuppliers(String supplierId,String bidStatus) {
        QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_id", supplierId);
        queryWrapper.eq("bid_status", bidStatus);
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    @Override
    public List<Bid> bidstatus(String isWinning) {
        QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_winning", isWinning);

        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }

    @Override
    public void addbiditem(String purchaseId,String LotteryId,String username) {
        PurchasePlan purchasePlan =purchasePlanService.getById(purchaseId);
        Lottery lottery =lotteryService.getById(LotteryId);
        Bid bid =new Bid();
//        项目类目，项目简述，项目联系人，联系电话，方案类型,工程名称，投标截止时间
        bid.setBidStatus("0");
        bid.setPurchaseId(purchaseId);
        bid.setBudgetAmount(purchasePlan.getBudgetAmount());
        bid.setProjectName(purchasePlan.getProjectName());
        bid.setSchemeType(purchasePlan.getSchemeType());
        bid.setOpeningTime(purchasePlan.getOpeningTime());
        bid.setBiddingEndTime(purchasePlan.getBiddingEndTime());
        bid.setCategory(purchasePlan.getCategory());
        bid.setCreateBy(username);
        bid.setLotteryId(LotteryId);
        bid.setCompanyName(lottery.getCompanyName());
        bid.setSupplierId(lottery.getSupplierId());
        bid.setCreateTime(new Date());
        // 保存到数据库
        boolean saveResult = this.save(bid);
        if (saveResult) {
            log.info("添加投标项目成功：采购方案ID={}，项目名称={}，创建人={}",
                    purchaseId, purchasePlan.getProjectName(), username);
        } else {
            log.error("添加投标项目失败：保存数据库失败，采购方案ID={}", purchaseId);
            throw new RuntimeException("保存投标记录失败");
        }
    }

    public Page<Bid> getBidsBySupplierId(String supplierId, Integer pageNo, Integer pageSize) {
        // 构建查询条件，根据supplierId查询proc_bid表
        QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_id", supplierId);

        // 分页查询
        Page<Bid> page = new Page<>(pageNo, pageSize);
        return this.page(page, queryWrapper);
    }


    public boolean selectWinner(String purchaseId, String username) {
        // 根据项目ID查找所有投标后的投标记录
        QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id", purchaseId);
        queryWrapper.eq("bid_status", "2"); // 已投标状态
        queryWrapper.orderByAsc("bid_price"); // 按价格升序排列
        List<Bid> bidList = this.list(queryWrapper);

        if (bidList == null || bidList.isEmpty()) {
            throw new RuntimeException("没有找到已投标的供应商");
        }

        // 获取最低报价的投标记录
        Bid lowestBid = bidList.get(0);

        // 更新最低报价供应商为中标状态
        lowestBid.setIsWinning(1); // 中标
        lowestBid.setBidStatus("4");
        lowestBid.setUpdateBy(username);
        lowestBid.setUpdateTime(new Date());
        boolean updateResult = this.updateById(lowestBid);
        //发送中标通知String bidId, String bidTitle, String receiverId, String receiver
        ProcUserSupplierRelation procUserSupplierRelation= procUserSupplierRelationService.getRelationBySearchKey(lowestBid.getSupplierId());
        procurementMessageService.sendWinningResultNotice(lowestBid.getId(),lowestBid.getProjectName(),procUserSupplierRelation.getUserId(),procUserSupplierRelation.getUsername());

        if (!updateResult) {
            return false;
        }

        // 更新其他供应商为未中标状态
        for (int i = 1; i < bidList.size(); i++) {
            Bid bid = bidList.get(i);
            bid.setIsWinning(0); // 未中标
            bid.setBidStatus("4");
            bid.setUpdateBy(username);
            bid.setUpdateTime(new Date());
            this.updateById(bid);
        }

        return true;
    }

    @Override
    public Bid getBysupplierId(String supplierId) {
        return null;
    }
}
